// 通过节点获取元素大小绘制canvas
import {
  alert,
  getSystemInfoSync
} from '../../js/newUtil'

let caches = {
  drawCanvasComplete: false,
  imgList: []
}

let drawCanvas = async (options) => {
  console.log(options)
  let {
    selector,
    autoSize
  } = options
  if (!selector) {
    return
  }
  caches.drawCanvasComplete = false
  caches.imgList = []
  // 如果不是从页面顶部开始绘制，需要传入绘制区域
  // 后续内容要根据绘制区域的左上角坐标调整
  if (options.drawAreaSelector) {
    let drawAreaInfo = await getViewSize(options.drawAreaSelector)
    if (drawAreaInfo && drawAreaInfo.length > 0) {
      if (drawAreaInfo[0].length > 0) {
        options.drawAreaInfo = drawAreaInfo[0][0]
      }
    }
  }
  // 不需要获取自动位置
  if (!autoSize) {
    console.log('autoSize disabled')
    getCtx(options)
    return
  }
  // 如果需要自动获取定位以及宽高
  getViewSize('.canvas-data-item').then((nodeDataList) => {
    nodeDataList = nodeDataList[0]
    if (options.data.node && options.data.node.length != 0) {
      for (let i in options.data.node) {
        const nodeItem = nodeDataList.shift()
        if (!nodeItem) {
          break
        }
        if (options.data.node[i].css) {
          options.data.node[i].css.left = nodeItem.left
          options.data.node[i].css.top = nodeItem.top
          options.data.node[i].css.width = nodeItem.width
          options.data.node[i].css.height = nodeItem.height
        } else {
          options.data.node[i].css = {
            left: nodeItem.left,
            top: nodeItem.top,
            height: nodeItem.height,
            width: nodeItem.width
          }
        }
      }
    }
    getCtx(options).catch((err) => {
      console.log('err=>', err)
    })
  })
}

let getCtx = (options) => {
  console.log(options)
  return new Promise((resolve, reject) => {
    let selector = options.selector
    let data = options.data || {}
    let scale = options.scale
    let drawAreaInfo = options.drawAreaInfo || {}
    scale = Number(scale)
    if (isNaN(scale)) {
      scale = 1
    }
    if (!scale) {
      scale = 1
    }
    const query = wx.createSelectorQuery()
    query.select(selector)
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        console.log('res', res)
        const canvas = res[0].node
        const width = res[0].width
        const height = res[0].height
        const ctx = canvas.getContext('2d')
        let dpr = getSystemInfoSync().pixelRatio
        dpr = 1
        canvas.width = width * dpr
        canvas.height = height * dpr
        ctx.scale(dpr, dpr)
        data.canvasHeight = height
        data.canvasWidth = width
        draw({
          canvas,
          ctx,
          scale,
          data,
          drawAreaInfo
        })
      })
    resolve('success')
  })
}

let draw = async (options) => {
  const {
    canvas,
    ctx,
    scale,
    data,
    drawAreaInfo
  } = options
  console.log(options)
  let top = 0
  // const SPLITHEIGHT = 500 // 分割图片的高度
  // let canvasNumber = Math.ceil(data.pageHeight / SPLITHEIGHT)
  // console.log(data)
  // console.log(SPLITHEIGHT)
  // console.log('绘制图片的张数')
  // console.log(canvasNumber)
  // if (isNaN(canvasNumber)) {
  //   canvasNumber = 4
  // }
  let canvasNumber = 1
  let SPLITHEIGHT = data.pageHeight
  if (!data.backgroundColor) {
    data.backgroundColor = '#ffffff'
  }
  for (let k = 0; k < canvasNumber; k++) {
    // 绘制图片背景
    fillRoundedRectangle({
      ctx,
      canvas,
      x: 0,
      y: 0,
      width: data.canvasWidth,
      height: data.canvasHeight,
      backgroundColor: data.backgroundColor
    })
    for (let i in data.node) {
      const item = data.node[i]
      let css = deepClone(item.css)
      css = unitsConversion({
        css,
        scale,
        drawAreaInfo
      })
      // let inblock = blockInCanvas({ css: css, width: data.canvasWidth * scale, height: SPLITHEIGHT * scale, x: 0 * scale, y: k * SPLITHEIGHT * scale })
      let inblock = true
      if (inblock) {
        ctx.save()
        await drawArea({
          ctx,
          canvas,
          item,
          css
        }).catch((err) => {
          console.log('绘制区域失败', err)
        })
        ctx.restore()
      }
    }
    await pushImgList({
      canvas,
      top: k * SPLITHEIGHT * scale
    }).catch((err) => {
      console.log('push 图片 至 数组失败', err)
    })
  }
  // fillRoundedRectangle({
  //   ctx,
  //   canvas,
  //   x: 0,
  //   y: 0,
  //   width: data.canvasWidth,
  //   height: data.canvasHeight,
  //   backgroundColor: '#ffffff'
  // })
  await getImgListBase64().catch((err) => {
    console.log('获取 imgList base64 失败', err)
  })
  caches.drawCanvasComplete = true
  console.log(caches)
  console.log('绘制canvas完成')
}

// 绘制某区域，顺序为背景颜色、背景图片、文字、边框
let drawArea = async (options) => {
  let ctx = options.ctx || {}
  let canvas = options.canvas || {}
  let css = options.css || {}
  let item = options.item || {}
  if (css.backgroundColor) {
    fillRoundedRectangle({
      ctx,
      canvas,
      height: css.height,
      width: css.width,
      x: css.x,
      y: css.y,
      borderRadius: css.borderRadius,
      backgroundColor: css.backgroundColor
    })
  }
  if (item.src) {
    await drawImage({
      ctx,
      canvas,
      height: css.height,
      width: css.width,
      x: css.x,
      y: css.y,
      borderRadius: css.borderRadius,
      borderWidth: css.borderWidth,
      borderColor: css.borderColor,
      src: item.src,
      mode: item.mode
    }).catch((err) => {
      console.log('绘制图片失败, 原内容为：', item)
      console.log(err)
    })
  }
  if (item.text) {
    setCtxText({
      ctx,
      canvas,
      height: css.height,
      width: css.width,
      x: css.x,
      y: css.y,
      fontSize: css.fontSize,
      fontWeight: css.fontWeight,
      color: css.color,
      textAlign: css.textAlign,
      textBaseline: css.textBaseline,
      maxLine: css.maxLine,
      padding: css.padding,
      text: item.text
    })
  }
  if (css.borderWidth) {
    strokeRoundedRectangle({
      ctx,
      canvas,
      height: css.height,
      width: css.width,
      x: css.x,
      y: css.y,
      borderRadius: css.borderRadius,
      borderWidth: css.borderWidth,
      borderColor: css.borderColor
    })
  }
}

// 绘制图片
let drawImage = async (options) => {
  console.log('--------------开始绘制图片---------------')
  let src = options.src || ''
  src = await changeSrc({
    src
  }).catch((err) => {
    console.log('获取图片失败, 原图片信息：', options)
    console.log(err)
  })
  console.log('获取图片src完成', src)
  return new Promise((resolve, reject) => {
    let ctx = options.ctx || {}
    let canvas = options.canvas || {}
    let x = options.x || 0
    let y = options.y || 0
    let width = options.width || 0
    let height = options.height || 0
    let borderRadius = options.borderRadius || 0
    let borderWidth = options.borderWidth || 0
    let borderColor = options.borderColor || '#ffffff'
    let mode = options.mode || 'scaleToFill' // 默认使用拉伸填充模式
    // 绘制border
    if (borderWidth > 0) {
      strokeRoundedRectangle({
        ctx,
        x: x,
        y: y,
        width: width,
        height: height,
        borderWidth,
        borderColor,
        borderRadius
      })
    }
    let img = canvas.createImage()
    img.src = src
    console.log('src', src)
    img.onload = () => {
      ctx.save()
      drawRectPath({
        ctx,
        x,
        y,
        width,
        height,
        borderRadius
      })
      ctx.clip()
      let imgHeight = img.height
      let imgWidth = img.width
      // 如果能获取到图片真实大小
      if (imgHeight && imgWidth) {
        let newOptions = imgMode({
          x,
          y,
          width,
          height,
          imgWidth,
          imgHeight,
          mode
        })
        x = newOptions.x
        y = newOptions.y
        height = newOptions.height
        width = newOptions.width
      }
      ctx.drawImage(img, x, y, width, height)
      ctx.restore()
      console.log('--------------绘制图片完成---------------')
      resolve('fill image success')
    }
    img.onerror = (err) => {
      console.log('图片加载错误', err)
      reject('fill image error')
    }
  })
}

// 勾勒路径
let drawRectPath = (options) => {
  let ctx = options.ctx || {}
  let x = options.x || 0
  let y = options.y || 0
  let width = options.width
  let height = options.height
  let borderRadius = options.borderRadius
  // ctx.translate(x, y)
  if (2 * borderRadius > width || 2 * borderRadius > height) {
    borderRadius = (Math.min(width, height)) / 2
  }
  ctx.beginPath()
  ctx.arc(x + width - borderRadius, y + height - borderRadius, borderRadius, 0, 0.5 * Math.PI)
  ctx.lineTo(x + borderRadius, y + height)
  ctx.arc(x + borderRadius, y + height - borderRadius, borderRadius, 0.5 * Math.PI, Math.PI)
  ctx.lineTo(x + 0, y + borderRadius)
  ctx.arc(x + borderRadius, y + borderRadius, borderRadius, Math.PI, 1.5 * Math.PI)
  ctx.lineTo(x + width - borderRadius, y + 0)
  ctx.arc(x + width - borderRadius, y + borderRadius, borderRadius, 1.5 * Math.PI, 2 * Math.PI)
  ctx.lineTo(x + width, y + height - borderRadius)
  ctx.closePath()
}

// 绘制空心圆角矩形
let strokeRoundedRectangle = (options) => {
  // ctx canvasContent， x 左上角横坐标， y 左上角纵坐标， width 矩形宽度， height 矩形高度，
  // borderRadius 圆角大小， lineWidth border宽度， strokeStyle border颜色
  let ctx = options.ctx || {}
  let x = options.x || 0
  let y = options.y || 0
  let width = options.width || 0
  let height = options.height || 0
  let borderRadius = options.borderRadius || 0
  let borderWidth = options.borderWidth || 1
  let borderColor = options.borderColor || '#ffffff'
  ctx.save()
  drawRectPath({
    ctx,
    x,
    y,
    width,
    height,
    borderRadius
  })
  ctx.lineWidth = borderWidth
  ctx.strokeStyle = borderColor
  ctx.stroke()
  ctx.restore()
}

// 绘制实心圆角矩形
let fillRoundedRectangle = (options) => {
  // ctx canvasContent， x 左上角横坐标， y 左上角纵坐标， width 矩形宽度， height 矩形高度，
  // borderRadius 圆角大小， backgroundColor 背景颜色
  let ctx = options.ctx || {}
  let x = options.x || 0
  let y = options.y || 0
  let width = options.width || 0
  let height = options.height || 0
  let borderRadius = options.borderRadius || 0
  let backgroundColor = options.backgroundColor || '#ffffff'
  ctx.save()
  drawRectPath({
    x,
    y,
    ctx,
    width,
    height,
    borderRadius
  })
  ctx.fillStyle = backgroundColor
  ctx.fill()
  ctx.restore()
}

// 绘制文字
let setCtxText = (options) => {
  // ctx canvasContent， x 左上角横坐标， y 左上角纵坐标， width 所在盒子宽度， height 所在盒子高度，
  // fontSize 字体大小， padding 左右边距， text 所绘制的文本 ，字体颜色 color
  let ctx = options.ctx || {}
  let x = options.x || 0
  let y = options.y || 0
  let width = options.width || 0
  let height = options.height || 0
  let fontSize = options.fontSize || 13
  let padding = options.padding || 0
  let textAlign = options.textAlign || 'center'
  let textBaseline = options.textBaseline || 'middle'
  let text = options.text || ''
  let fontWeight = options.fontWeight || 'normal'
  let color = options.color || ''
  let maxLine = options.maxLine || ''
  if (text == '') {
    return
  }
  if (fontSize !== '') {
    ctx.font = `${fontSize}px ${fontWeight} sans-serif`
  }
  if (color !== '') {
    ctx.fillStyle = color
  }
  if (fontWeight == 'bold') {
    options.fontWeight = 'normal'
  }
  ctx.textAlign = textAlign
  ctx.textBaseline = textBaseline
  let textArr = []
  let temp = ''
  for (let i = 0; i < text.length; i++) {
    if (ctx.measureText(temp).width >= (width - 2 * padding)) {
      textArr.push(temp)
      temp = ''
    }
    temp += text[i]
  }
  if (temp != '') {
    textArr.push(temp)
  }
  // 超过限定行数显示 ... 结尾
  if (maxLine != '') {
    if (textArr.length > maxLine) {
      textArr.length = maxLine
      if (textArr.length > 0) {
        let lastLine = textArr[textArr.length - 1]
        let chineseReg = /[\u4e00-\u9fa5]+$/
        if (lastLine.length > 3) {
          if (chineseReg.test(lastLine)) {
            lastLine = lastLine.substr(0, lastLine.length - 1)
          } else {
            lastLine = lastLine.substr(0, lastLine.length - 2)
          }
          lastLine = lastLine + '...'
          textArr[textArr.length - 1] = lastLine
        }
      }
    }
  }
  for (let i = 0; i < textArr.length; i++) {
    let line = y
    let start = x
    let textWidth = width
    if (padding && (2 * padding) < width) {
      start = x + padding
      textWidth = width - (2 * padding)
    }
    // 计算每行文字所在的y轴值
    if (textBaseline == 'top') {
      line = y + (i * fontSize)
    } else if (textBaseline == 'middle') {
      line = y + (height / 2) + ((i + 0.5 - (textArr.length / 2)) * fontSize)
    } else if (textBaseline == 'bottom') {
      line = y + height - ((textArr.length - i - 1) * fontSize)
    }
    if (ctx.textAlign == 'center') {
      ctx.fillText(textArr[i], start + (textWidth / 2), line, textWidth)
    } else if (ctx.textAlign == 'left') {
      ctx.fillText(textArr[i], start, line, textWidth)
    } else if (ctx.textAlign == 'right') {
      ctx.fillText(textArr[i], start + textWidth, line, textWidth)
    }
  }
  // 加粗字体，则将整个文字内容移动1像素后，再次绘制
  if (fontWeight == 'bold') {
    setCtxText(options)
  }
}

// 图片mode，获取图片真实位置及大小
let imgMode = (options) => {
  let {
    x,
    y,
    width,
    height,
    imgWidth,
    imgHeight,
    mode
  } = options
  let halfX = x + ((width - imgWidth) / 2)
  let fullX = x + width - imgWidth
  let halfY = y + ((height - imgHeight) / 2)
  let fullY = y + height - imgHeight
  let zoomMode = ['scaleToFill', 'aspectFit', 'aspectFill', 'widthFix', 'heightFix']
  let cutMode = ['top', 'bottom', 'center', 'left', 'right', 'top left', 'top right', 'bottom left', 'bottom right']
  // 缩放拉伸模式，无需处理
  if (mode == 'scaleToFill') {
    return options
  }
  // // 宽高相等并且为缩放模式，则无需处理
  // if (imgWidth == imgHeight) {
  //   if (zoomMode.includes(mode)) {
  //     return options
  //   }
  // }
  // 裁剪模式,根据不同模式确定该模式下的x,y定位
  if (cutMode.includes(mode)) {
    options.height = imgHeight
    options.width = imgWidth
    if (mode == 'top left') {}
    if (mode == 'top') {
      options.x = halfX
    }
    if (mode == 'top right') {
      options.x = fullX
    }
    if (mode == 'left') {
      options.y = halfY
    }
    if (mode == 'center') {
      options.x = halfX
      options.y = halfY
    }
    if (mode == 'right') {
      options.x = fullX
      options.y = halfY
    }
    if (mode == 'bottom left') {
      options.y = fullY
    }
    if (mode == 'bottom') {
      options.x = halfX
      options.y = fullY
    }
    if (mode == 'bottom right') {
      options.x = fullX
      options.y = fullY
    }
    return options
  }
  // 拉伸模式
  if (zoomMode.includes(mode)) {
    // aspectFit模式
    if (mode == 'aspectFit') {
      let changeType = 'height'
      let ratio1 = imgHeight / imgWidth // 图片真实宽高比
      let ratio2 = height / width // 当前显示区域宽高比
      if (imgWidth > imgHeight) {
        // 当原图片宽度大于高度时
        if (ratio1 > ratio2) {
          // 实际宽高比大于显示区域宽高比时，需要改变宽度
          // 高度占满，两侧留出区域
          changeType = 'width'
        } else {
          // 实际宽高比小于显示区域宽高比时，需要改变高度
          // 高度占满，上下留出区域
          changeType = 'height'
        }
      } else {
        // 当原图片宽度小于高度时
        if (ratio1 > ratio2) {
          // 实际宽高比大于显示区域宽高比时，需要改变高度
          // 宽度占满，上下留出区域
          changeType = 'height'
        } else {
          // 实际宽高比小于显示区域宽高比时，需要改变宽度
          // 高度占满，左右留出区域
          changeType = 'width'
        }
      }
      if (changeType == 'height') {
        let newHeight = imgHeight * width / imgWidth
        options.height = newHeight
        options.y = y + ((height - newHeight) / 2)
      } else {
        let newWidth = imgWidth * height / imgHeight
        options.width = newWidth
        options.x = x + ((width - newWidth) / 2)
      }
    }
    // widthFix 和 heightFix
    if (mode == 'widthFix' || mode == 'heightFix') {
      if (imgWidth > imgHeight) {
        let newHeight = imgHeight * width / imgWidth
        options.height = newHeight
        options.y = y + ((height - newHeight) / 2)
      } else {
        let newWidth = imgWidth * height / imgHeight
        options.width = newWidth
        options.x = x + ((width - newWidth) / 2)
      }
    }
    if (mode == 'aspectFill') {
      if (imgWidth > imgHeight) {
        let newWidth = imgWidth * height / imgHeight
        options.width = newWidth
        options.x = x + ((width - newWidth) / 2)
      } else {
        let newHeight = imgHeight * width / imgWidth
        options.height = newHeight
        options.y = y + ((height - newHeight) / 2)
      }
    }
    return options
  }
  return options
}

// 将css中的数值转换
let unitsConversion = (options) => {
  console.log('unitsConversion', options)
  let {
    css,
    scale,
    drawAreaInfo
  } = options
  // 获取绘制区域的左上角左边
  // 所有绘制内容的坐标需要减去绘制区域的坐标
  css.x = rpxToPx(css.x || css.left)
  css.y = rpxToPx(css.y || css.top)
  if (drawAreaInfo) {
    css.x -= drawAreaInfo.left
    css.y -= drawAreaInfo.top
  }
  css.x = css.x * scale
  css.y = css.y * scale
  css.height = rpxToPx(css.height) * scale
  css.width = rpxToPx(css.width) * scale
  css.fontSize = rpxToPx(css.fontSize) * scale
  if (/%$/.test(css.borderRadius)) {
    let radius = Number(css.borderRadius.replace('%', ''))
    if (!isNaN(radius)) {
      if (radius > 50) {
        radius = 50
      }
      radius /= 100
      css.borderRadius = (Math.min(css.width, css.height)) * radius * scale
    } else {
      css.borderRadius = 0
    }
  } else {
    css.borderRadius = rpxToPx(css.borderRadius) * scale
  }
  css.borderWidth = rpxToPx(css.borderWidth) * scale
  return css
}

// rpx单位转换为px单位, 返回一个代表px值的数字
let rpxToPx = (str = '') => {
  if (str === Number(str)) {
    return str
  }
  let rpxWidth = 750
  let systemInfo = getSystemInfoSync()
  let windowWidth = systemInfo.windowWidth
  let pxReg = /px$/
  let rpxReg = /rpx$/
  if (rpxReg.test(str)) {
    str = str.replace(rpxReg, '')
    str = Number(str)
    str = windowWidth * str / 750
  } else if (pxReg.test(str)) {
    str = str.replace(pxReg, '')
    str = Number(str)
  } else {
    str = Number(str)
  }
  if (isNaN(str)) {
    return 0
  } else {
    return str
  }
}

// 获取元素属性
let getViewSize = (selector = '') => {
  return new Promise((resolve, reject) => {
    wx.createSelectorQuery().selectAll(selector).boundingClientRect().exec((res) => {
      resolve(res)
    })
  })
}

// 获取元素列表属性
let getViewListSize = (selectorList = []) => {
  let promiseList = []
  let resultList = []
  return new Promise((resolve, reject) => {
    for (let i = 0; i < selectorList.length; i++) {
      promiseList.push(getViewSize(selectorList[i]))
    }
    Promise.all(promiseList).then((res) => {
      for (let i = 0; i < selectorList.length; i++) {
        const temp = {
          list: res.shift(),
          selector: selectorList[i]
        }
        resultList.push(temp)
      }
      console.log(resultList)
      resolve(resultList)
    }).catch((err) => {
      console.log('获取元素属性出错')
      reject(err)
    })
  })
}

let pushImgList = (options) => {
  let canvas = options.canvas || ''
  let top = options.top || 0
  return new Promise((resolve) => {
    wx.canvasToTempFilePath({
      canvas,
      success(res) {
        wx.getImageInfo({
          src: res.tempFilePath,
          success(info) {
            caches.imgList.push({
              src: res.tempFilePath,
              top: top,
              width: info.width,
              height: info.height
            })
            resolve('save img success')
          },
          fail(err) {
            resolve('save img fail')
          }
        })
      },
      fail(err) {
        resolve('save img fail')
      }
    })
  })
}

let clearImgList = () => {
  caches.imgList = []
}

let getImgList = () => {
  return new Promise((resolve) => {
    const TIMEOUT = 60000
    const STEP = 500
    let time = 0
    let interval = setInterval(() => {
      console.log(caches)
      if (time > TIMEOUT) {
        clearInterval(interval)
        resolve([])
      } else {
        if (caches.drawCanvasComplete) {
          clearInterval(interval)
          resolve(caches.imgList)
        } else {
          time += STEP
        }
      }
    }, STEP)
  })
}

let changeSrc = (options) => { // 对于大图片，需要先下载
  let src = options.src || ''
  return new Promise((resolve, reject) => {
    if (src == '') {
      resolve('')
      return
    }
    src = src.replace('http://', 'https://') // 替换图片为https
    wx.getImageInfo({
      src: src,
      success(res) {
        console.log('canvas get image info success', res)
        resolve(res.path)
      },
      fail(err) {
        console.log('canvas get image info error', err)
        src = src.replace('https://', 'http://') // 本地图片
        resolve(src)
      }
    })
  })
}

// 保存canvas内容至相册
let saveImage = (canvasSelector, canvasInfo) => {
  if (!wx.createOffscreenCanvas) {
    alert({
      title: '未保存',
      content: '您当前客户端版本不支持保存，请手动截图，或者更新后再使用此功能'
    })
    return
  }
  if (!caches.drawCanvasComplete) {
    alert('图片尚未生成，请等待一会后保存')
    return
  }
  wx.showLoading({
    content: '生成图片中...',
  })
  const query = wx.createSelectorQuery()
  query.select(canvasSelector)
    .fields({
      node: true,
      size: true
    })
    .exec((res) => {
      const canvasNode = res[0].node
      const dpr = getSystemInfoSync().pixelRatio
      wx.canvasToTempFilePath({
        canvas: canvasNode,
        // width: canvasInfo.width,
        // height: canvasInfo.height,
        // destHeight: canvasInfo.height * dpr * dpr,
        // destWidth: canvasInfo.width * dpr * dpr,
        // fileType: 'jpg',
        quality: 1,
        success(res) {
          wx.hideLoading()
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success() {
              alert('保存成功')
            },
            fail(err) {
              if (err.errMsg == "saveImageToPhotosAlbum:fail cancel") {
                alert('用户取消')
              } else {
                alert({
                  title: '未保存',
                  content: '保存图片至相册失败，可能是由于您未授权，请进入设置中，去开启相应权限'
                })
              }
            }
          })
        },
        fail(err) {
          console.log(err)
        }
      })
    })
}

let imgToBase64 = (options) => {
  let src = options.src
  let result = options
  return new Promise((resolve) => {
    wx.getFileSystemManager().readFile({
      filePath: src,
      encoding: 'base64',
      success(res) {
        result.base64 = res.data
        resolve(result)
      },
      fail() {
        resolve(result)
      }
    })
  })
}

let getImgListBase64 = () => {
  let promiseList = []
  for (let i in caches.imgList) {
    promiseList.push(imgToBase64(caches.imgList[i]))
  }
  return new Promise((resolve) => {
    Promise.all(promiseList).then((res) => {
      resolve(res)
    })
  })
}

// 判断绘制的内容是否在与某区域相交
let blockInCanvas = (options) => {
  let css = options.css || {}
  let width = options.width || 0
  let height = options.height || 0
  let x = options.x
  let y = options.y
  let overlapX = width + css.width - (Math.max(x + width, css.x + css.width) - Math.min(x, css.x))
  let overlapY = height + css.height - (Math.max(y + height, css.y + css.height) - Math.min(y, css.y))
  if (overlapX <= 0 || overlapY <= 0) {
    return false
  }
  return true
}

// 定义一个深拷贝函数  接收目标target参数
let deepClone = (target) => {
  // 定义一个变量
  let result;
  // 如果当前需要深拷贝的是一个对象的话
  if (typeof target === 'object') {
    // 如果是一个数组的话
    if (Array.isArray(target)) {
      result = []; // 将result赋值为一个数组，并且执行遍历
      for (let i in target) {
        // 递归克隆数组中的每一项
        result.push(deepClone(target[i]))
      }
      // 判断如果当前的值是null的话；直接赋值为null
    } else if (target === null) {
      result = null;
      // 判断如果当前的值是一个RegExp对象的话，直接赋值    
    } else if (target.constructor === RegExp) {
      result = target;
    } else {
      // 否则是普通对象，直接for in循环，递归赋值对象的所有值
      result = {};
      for (let i in target) {
        result[i] = deepClone(target[i]);
      }
    }
    // 如果不是对象的话，就是基本数据类型，那么直接赋值
  } else {
    result = target;
  }
  // 返回最终结果
  return result;
}

let reset = () => {
  caches.drawCanvasComplete = false
  caches.imgList = []
}


export {
  drawCanvas,
  saveImage,
  getViewListSize,
  clearImgList,
  getImgList,
  getImgListBase64,
  drawImage, // 绘制图片
  drawRectPath, // 绘制路径
  setCtxText, // 绘制文字
  strokeRoundedRectangle, // 空心圆角矩形
  fillRoundedRectangle, // 实心圆角矩形
  reset
}